define(['app', 'sql-formatter', 'ace-language-tools'], function(app, sqlFormatter) {
    app.controller('SqlMatcherController', function($scope, $compile, xUtil) {
        var self = this;
        self.preparingSql = '';
        self.parameters = '';
        self.code = '';

        const quotTypes = ['String', 'Date', 'Timestamp'];
        var sqlViewer = null;

        self.init = function() {
            self.preparingSql = 'SELECT * FROM users WHERE username = ? AND password = ?';
            self.parameters = 'admin(String), 123456(String)';

            xUtil.clipboard.copy('#copy', function() {
                return self.code;
            });

            // Sql viewer
            sqlViewer = ace.edit('sql-viewer', {
                mode: 'ace/mode/sql',
                theme: 'ace/theme/chrome',
                fontSize: 14,
                readOnly: true,
                useWorker: false,
                showPrintMargin: false,
                highlightGutterLine: false,
                highlightActiveLine: false,
                autoScrollEditorIntoView: true
            });

            $scope.$watch('vm.code', function(newValue) {
                sqlViewer.setValue(newValue, -1);
                sqlViewer.resize();
            });
        }

        self.callback = function(height, width, refresh) {
            $('.x-view-scope textarea').height((height - 93)/2);
            // Toolbar
            if (refresh) {
                $('.navbar-form').append($compile($('#opt-toolbar').html())($scope));
            }
        }

        self.reset = function() {
            self.preparingSql = '';
            self.parameters = '';
            self.code = '';
        }

        self.match = function(valid) {
            if (valid) {
                var parameters = [];
                angular.forEach(self.parameters.split(','), function(parameter) {
                    parameter = parameter.trim();
                    var value = parameter.replace(/\([^\(\)]+\)$/, '');
                    var type = parameter.substring(value.length).replace(/\(|\)/g, '');
                    if (quotTypes.indexOf(type) >= 0) {
                        value = "'" + value + "'";
                    }
                    parameters.push(value);
                });

                self.code = sqlFormatter.format(self.preparingSql, {
                    indent: '    ',
                    language: 'sql',
                    params: parameters
                });
            }
        }
    });
});
